package com.xinghai.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xinghai.common.annotation.Log;
import com.xinghai.common.config.XingHaiConfig;
import com.xinghai.common.core.controller.BaseController;
import com.xinghai.common.core.domain.AjaxResult;
import com.xinghai.common.core.domain.model.LoginUser;
import com.xinghai.common.core.redis.RedisCache;
import com.xinghai.common.enums.BusinessType;
import com.xinghai.common.utils.DateUtils;
import com.xinghai.common.utils.PageUtils;
import com.xinghai.common.utils.StringUtils;
import com.xinghai.common.utils.file.FileUploadUtils;
import com.xinghai.common.utils.file.FileUtils;
import com.xinghai.common.utils.file.MimeTypeUtils;
import com.xinghai.common.utils.file.SysFile;
import com.xinghai.common.utils.uuid.IdUtils;
import com.xinghai.domain.*;
import com.xinghai.service.*;
import com.xinghai.wechat.WeChatService;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static cn.binarywang.wx.miniapp.constant.WxMaConstants.DEFAULT_ENV_VERSION;


@RestController
@RequestMapping("/api/person")
public class ApiPersonController extends BaseController {

    @Autowired
    private WxMaService maService;

    @Autowired
    private IJkqUserService userService;

    @Autowired
    private IJkqBadgeService badgeService;

    @Autowired
    private IJkqActivityService jkqActivityService;

    @Autowired
    private IJkqActivitySignService activitySignService;

    @Autowired
    private IJkqActivityShareService activityShareService;

    @Autowired
    private IJkqUserBadgeService userBadgeService;


    @Autowired
    private RedisCache redisCache;

    /**
     * 报名活动
     * @param activityId
     * @return
     */
    @PostMapping("/sign")
    public AjaxResult sign(@RequestBody JkqActivitySign activitySign) {
        Long activityId = activitySign.getActivityId();
        JkqActivity activity = jkqActivityService.getById(activityId);
        if (activity == null) {
            return error("活动不存在");
        }
        if (activity.getStartTime().compareTo(new Date()) > 0){
            return error("活动未开始");
        }
        if (activity.getEndTime().compareTo(new Date()) < 0){
            return error("活动已结束");
        }
        if (activity.getLimitNum()>0 && activity.getSignNum() >= activity.getLimitNum()) {
            return error("活动报名人数已满");
        }
        Long loginId = StpUtil.getLoginId(0L);
        JkqUser user = userService.getById(loginId);
        if (user == null) {
            return new AjaxResult(401,"登录失效，请重新登录");
        }
        activitySign.setUserName(user.getNickname());
        activitySign.setUserImage(user.getImageUrl());
        activitySign.setType(activity.getType());
        if (activitySignService.isSign(activityId, loginId)) {
            return error("您已报名该活动，请勿重复报名");
        }
        activitySign.setUserId(loginId);
        activitySignService.sign(activitySign);
        return success();
    }

    @GetMapping("getQrCode")
    public void getQrCode(Long activityId,Long userId, HttpServletResponse response) {
        try {
            String wxAccessToken = redisCache.getCacheObject("wx_accessToken");
            if (StringUtils.isBlank(wxAccessToken)){
                wxAccessToken = maService.getAccessToken();
                redisCache.setCacheObject("wx_accessToken", wxAccessToken,60*45*2, TimeUnit.SECONDS);
            }
            String scene = "id=" + activityId + (userId!=null? "&u=" + userId : "");
            File wxaCodeUnlimit = maService.getQrcodeService().createWxaCodeUnlimit( scene , "pages/detail/index",true , DEFAULT_ENV_VERSION, 430, true, null, false);
            response.setContentType("image/jpeg");
            FileUtils.writeBytes(wxaCodeUnlimit, response.getOutputStream());
        } catch (WxErrorException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取用户信息
     * @return
     */
    @GetMapping("/getInfo")
    public AjaxResult getInfo() {
        Long loginId = StpUtil.getLoginId(0L);
        JkqUser user = userService.getById(loginId);
        user.setOpenId( null);
        user.setPassword( null);
        if (!"0".equals(user.getStatus())){
            StpUtil.logout();
            return new AjaxResult(401,"该账号被禁用");
        }
        //刷新登录状态
        if (DateUtils.belongCalendarBefore(DateUtils.dateTime(user.getLastLoginTime()))){
            user.setLoginNum(user.getLoginNum()+1);
            user.setLastLoginTime(DateUtils.getNowDate());
            userService.updateById(user);
            //查看是否有获得的徽章
            BadgeItem badgeItem = new BadgeItem();
            badgeItem.setNum(user.getLoginNum());
            badgeItem.setUserId(user.getId());
            badgeItem.setType("1");
            badgeService.getBadgePower(badgeItem);
        }
        return success(user);
    }



    /**
     * 头像上传
     */
    @PostMapping("/avatar")
    public AjaxResult avatar(@RequestParam("avatarfile") MultipartFile file,@RequestParam(required = false,name = "nickName")String nickName) throws Exception
    {
        if (!file.isEmpty())
        {
            Long loginId = StpUtil.getLoginId(0L);
            SysFile sysFile = FileUploadUtils.upload(XingHaiConfig.getAvatarPath(), file, MimeTypeUtils.IMAGE_EXTENSION);
            String avatar = sysFile.getFileUploadPath();
            JkqUser user = new JkqUser();
            user.setId(loginId);
            user.setImageUrl(avatar);
            if (StringUtils.isNotBlank(nickName)){
                user.setNickname(nickName);
            }
            if (userService.updateById(user))
            {
                AjaxResult ajax = AjaxResult.success();
                ajax.put("imgUrl", avatar);
                return ajax;
            }
        }
        return error("上传图片异常，请联系管理员");
    }

    /**
     * 修改信息
     * @param user
     * @return
     */
    @PostMapping("/update")
    public AjaxResult update(@RequestBody JkqUser user) {
        Long loginId = StpUtil.getLoginId(0L);
        user.setId(loginId);
        user.setUpdateTime(new Date());
        return toAjax(userService.updateById(user));
    }

    /**
     * 分享
     * @param activityId
     * @return
     */
    @PostMapping("/share")
    public AjaxResult share(Long activityId) {
        Long loginId = StpUtil.getLoginId(0L);
        JkqActivityShare activityShare = new JkqActivityShare();
        activityShare.setActivityId(activityId);
        activityShare.setUserId(loginId);
        JkqActivity activity = jkqActivityService.getById(activityId);
        if (activity == null){
            return success();
        }
        JkqUser user = userService.getById(loginId);
        if (user == null) {
            return success();
        }
        QueryWrapper<JkqActivityShare> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("activity_id", activityId);
        queryWrapper.eq("user_id", loginId);
        JkqActivityShare shareServiceOne = activityShareService.getOne(queryWrapper);
        if (shareServiceOne != null){
            activityShare.setUpdateTime(new Date());
            activityShareService.updateById(activityShare);
            return success();
        }
        activityShare.setUserName(user.getNickname());
        activityShare.setUserImage(user.getImageUrl());
        activityShare.setType(activity.getType());
        activityShare.setShareNum(0);
        activityShare.setSignNum(0);
        activityShare.setUpdateTime(new Date());
        activityShare.setCreateTime(new Date());
        activityShareService.share(activityShare);
        return success();
    }

    /**
     * 获取用户徽章
     * @return
     */
    @GetMapping("/badge")
    public AjaxResult badge(Integer pageSize) {
        Long loginId = StpUtil.getLoginId(0L);
        List<JkqBadge> list = userBadgeService.getByUserId(loginId,pageSize);
        return success(list);
    }

    /**
     *  获取用户分享
     * @return
     */
    @GetMapping("/myShare")
    public AjaxResult myShare(String status) {
        Long loginId = StpUtil.getLoginId(0L);
        startPage();
        List<JkqActivityShare> list = activityShareService.getInfoByUserId(loginId,status);
        return success(getDataTable(list));
    }

    /**
     *  获取用户报名
     * @return
     */
    @GetMapping("/mySign")
    public AjaxResult mySign(String status) {
        Long loginId = StpUtil.getLoginId(0L);
        startPage();
        if ("0".equals(status)){
            status = null;
        }else if ("1".equals(status)){
            status = "0";
        }else if ("2".equals(status)){
            status = "1";
        }else if ("3".equals(status)){
            status = "2";
        }
        List<JkqActivitySign> list = activitySignService.getInfoByUserId(loginId,status);
        return success(getDataTable(list));
    }



}
